<?php

namespace App\Models\Goods;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GoodsCate extends Model
{
    //使用软删除
    use SoftDeletes;
    //关联表
    protected $table = 'goods_cate';
    //填充字段
    protected $fillable = ['pid','name','description'];
    //设置主键
    protected $primaryKey = 'id';
    //软删除自动维护字段,不为空时此条数据不显示
    protected $dates = ['deleted_at'];
    /**
     * validate 表单数据验证
     *
     * @param $data
     * @return bool
     */
    public  static function validate($data){
        return  Validator::make($data, [
            'name'=>'required',
//            'description'=>'required',
        ],[
                'name.required' => '别名必填！',
//                'description.required' => '描述必填！',
            ]
        );
    }

    /**
     * childCategory 主外键关联
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function childCategory() {
        return $this->hasMany('App\Models\Goods\GoodsCate', 'pid', 'id');
    }

    /**
     * allChildrenCategorys 数据关联
     *
     * @return $this
     */
    public function allChildrenCategorys()
    {
        return $this->childCategory()->with('allChildrenCategorys');
    }
    /**
     * getCategory 递归查找
     * @param $sourceItems array 原数组
     * @param $targetItems array  重组后的数组
     * @param int $pid 父id
     * @param string $str 展现形式
     * @param int $i 控制空格数量
     */
    public function getCategory($sourceItems, $targetItems, $pid=0, $str='',$i=0){
        $str .= $i>=1 ? "&nbsp;&nbsp;├&nbsp;&nbsp;":'';
        foreach ($sourceItems as $k => $v) {
            if($v->pid == $pid){
                $v->num = substr_count($str,"├")+1;
                $targetItems[] = $v;
                $i++;
                $this->getCategory($sourceItems, $targetItems, $v->id, $str,$i);
            }
        }
    }

    /**
     * getCategoryInfo 获取栏目相关信息
     *
     * @param boolean $softDel 是否查询软删除数据
     * @return Collection
     */
    public function getCategoryInfo($softDel = true){
        $collection = $softDel ? GoodsCate::withoutTrashed() : GoodsCate::onlyTrashed();
        $sourceItems = $collection->get();
        //调整多级下拉菜单样式
        $pids = DB::table('goods_cate')->pluck('pid')->unique();
        $sourceItems->each(function($item) use( $pids){
            $item->child = $pids->search($item->id)?'yes':'non';
        });
        if(!$softDel) return $sourceItems;
        $targetItems = new Collection();
        $this->getCategory($sourceItems, $targetItems);
        return $targetItems;
    }
}
